import {otherRouter, appRouter} from '@/router/router';
import Util from '@/libs/util';
import Cookies from 'js-cookie';
import Vue from 'vue';

import * as api from '@/services/app'
// import io from 'socket.io-client';
const app = {
  state: {
    routers: [
      otherRouter,
      ...appRouter
    ],
		menus: [],
    currentUser: {},
    currentPermission: [],
    lang: '',
    isFullScreen: false,
    tagsList: [...otherRouter.children],
    pageOpenedList: [{
        title: '首页',
        path: '',
        name: 'home_index'
    }],
    currentPageName: '',
    currentPath: [
        {
            title: '首页',
            path: '',
            name: 'home_index'
        }
    ],  // 面包屑数组
    openedSubmenuArr: [],  // 要展开的菜单数组
    menuTheme: 'dark', // 主题
    theme: '',
    cachePage: [],
    lang: '',
    receiveMessage: {},
    isFullScreen: false,
    dontCache: ['text-editor']  // 在这里定义你不想要缓存的页面的name属性值(参见路由配置router.js)
  },
  mutations: {
    SET_USER: (state, user) => {
			state.currentUser = user
		},
		SET_MENUS: (state, menus) => {
			state.menus = menus
    },
    SET_PERMISSION: (state, permission) => {
      state.currentPermission = permission
    },
    receiveMessage: (state, data) => {
      console.log(data)
    },
		DoUpdateMenu: (state, hasPermissions) => {
      let menuList = [];
      const accessCode = 1;
			appRouter.forEach((item, index) => {
        //access已定义，且值1，表示此路由需要权限要求
        if (item.access !== undefined && item.access === 1) {
            if (Util.showThisRoute(item.name, hasPermissions)) {
                if (item.children.length === 1) {
                    menuList.push(item);
                } else {
                    let len = menuList.push(item);
                    let childrenArr = [];
                    childrenArr = item.children.filter(child => {
                        if (child.access !== undefined && child.access === 1) {
                          if (Util.showThisRoute(child.name, hasPermissions)) {
                                return child;
                            }
                        } else {
                            return child;
                        }
                    });
                    menuList[len - 1].children = childrenArr;
                }
            }
        } else {
            if (item.children.length === 1) {
                menuList.push(item);
            } else {
                let len = menuList.push(item);
                let childrenArr = [];
                childrenArr = item.children.filter(child => {
                    if (child.access !== undefined && item.access === 1) {
                        if (Util.showThisRoute(child.name, hasPermissions)) {
                            return child;
                        }
                    } else {
                        return child;
                    }
                });
                let handledItem = JSON.parse(JSON.stringify(menuList[len - 1]));
                handledItem.children = childrenArr;
                menuList.splice(len - 1, 1, handledItem);
            }
        }
			});
			state.menus = menuList;
    },
    setTagsList (state, list) {
      state.tagsList.push(...list);
    },
    closePage (state, name) {
        state.cachePage.forEach((item, index) => {
            if (item === name) {
                state.cachePage.splice(index, 1);
            }
        });
    },
    initCachepage (state) {
      if (localStorage.cachePage) {
          state.cachePage = JSON.parse(localStorage.cachePage);
      }
    },
    removeTag (state, name) {
        state.pageOpenedList.map((item, index) => {
            if (item.name === name) {
                state.pageOpenedList.splice(index, 1);
            }
        });
    },
    //设置打开的页面
    pageOpenedList (state, get) {
        let openedPage = state.pageOpenedList[get.index];
        if (get.argu) {
            openedPage.argu = get.argu;
        }
        if (get.query) {
            openedPage.query = get.query;
        }
        state.pageOpenedList.splice(get.index, 1, openedPage);
        // localStorage.pageOpenedList = JSON.stringify(state.pageOpenedList);
    },
    increateTag (state, tagObj) {
        if (!Util.oneOf(tagObj.name, state.dontCache)) {
            if(!state.cachePage.includes(tagObj.name)) {
              state.cachePage.push(tagObj.name);
            }
            //打开标签的页面需要写入缓存
            localStorage.cachePage = JSON.stringify(state.cachePage);
        }
        state.pageOpenedList.push(tagObj);
        localStorage.pageOpenedList = JSON.stringify(state.pageOpenedList);
    },
    clearAllTags (state, router) {
      state.pageOpenedList.splice(1);
      router.push({
          name: 'home_index'
      });
      state.cachePage.length = 0;
      localStorage.pageOpenedList = JSON.stringify(state.pageOpenedList);
    },
    clearOtherTags (state, vm) {
      let currentName = vm.$route.name;
      let currentIndex = 0;
      state.pageOpenedList.forEach((item, index) => {
          if (item.name === currentName) {
              currentIndex = index;
          }
      });
      if (currentIndex === 0) {
          state.pageOpenedList.splice(1);
      } else {
          state.pageOpenedList.splice(currentIndex + 1);
          state.pageOpenedList.splice(1, currentIndex - 1);
      }
      let newCachepage = state.cachePage.filter(item => {
          return item === currentName;
      });
      state.cachePage = newCachepage;
      localStorage.pageOpenedList = JSON.stringify(state.pageOpenedList);
    },
    setOpenedList (state) {
      //初始化时打开已经缓存的标签,否则默认打开第一个
      state.pageOpenedList = localStorage.pageOpenedList ? JSON.parse(localStorage.pageOpenedList) : [otherRouter.children[0]];
    },
    setCurrentPath (state, pathArr) {
      state.currentPath = pathArr;
    },
    setCurrentPageName (state, name) {
        state.currentPageName = name;
    },
    addOpenSubmenu (state, name) {
        let hasThisName = false;
        let isEmpty = false;
        if (name.length === 0) {
            isEmpty = true;
        }
        if (state.openedSubmenuArr.indexOf(name) > -1) {
            hasThisName = true;
        }
        if (!hasThisName && !isEmpty) {
            state.openedSubmenuArr.push(name);
        }
    },
    clearOpenedSubmenu (state) {
      state.openedSubmenuArr.length = 0;
    },
    changeMenuTheme (state, theme) {
        state.menuTheme = theme;
    },
    changeMainTheme (state, mainTheme) {
        state.theme = mainTheme;
    },
    lock (state) {
        Cookies.set('locking', '1');
    },
    unlock (state) {
        Cookies.set('locking', '0');
    },
    setMenuList (state, menulist) {
        state.menuList = menulist;
    },
    setAvator (state, path) {
      localStorage.avatorImgPath = path;
    },
    switchLang (state, lang) {
        state.lang = lang;
        Vue.config.lang = lang;
    },
    handleFullScreen (state) {
      let main = document.body;
      if (state.isFullScreen) {
          if (document.exitFullscreen) {
              document.exitFullscreen();
          } else if (document.mozCancelFullScreen) {
              document.mozCancelFullScreen();
          } else if (document.webkitCancelFullScreen) {
              document.webkitCancelFullScreen();
          } else if (document.msExitFullscreen) {
              document.msExitFullscreen();
          }
      } else {
          if (main.requestFullscreen) {
              main.requestFullscreen();
          } else if (main.mozRequestFullScreen) {
              main.mozRequestFullScreen();
          } else if (main.webkitRequestFullScreen) {
              main.webkitRequestFullScreen();
          } else if (main.msRequestFullscreen) {
              main.msRequestFullscreen();
          }
      }
    },
    changeFullScreenState (state) {
        state.isFullScreen = !state.isFullScreen;
    }
  },
  actions: {
		async DoLogin({ rootState, commit }, payload) {
			return await api.login(payload)
    },
    //初始化信息，由main.js调
		async DoGetUserInfo({ commit, dispatch }, payload) {
      //请求后端获取用户、权限信息
			const response = await api.current()
			if (response) {
				const { data } = response
				if (data) {
          const { hasMenus, hasPermissions, hasRoles, sysUser } = data
					//设置权限信息到本地
					// localStorage.setItem('has_permissions', hasPermissions);
					//设置角色信息到本地
					// localStorage.setItem('has_roles', hasRoles);
					//设置菜单信息到本地
					// localStorage.setItem('has_menus', JSON.stringify(hasMenus));
          // commit('SET_USER', data)\
          localStorage.avatorPath = sysUser.avatar;
          localStorage.username = sysUser.username;
          localStorage.userId = sysUser.id;
          localStorage.permission = JSON.stringify(hasPermissions);

          // Util.createSocket(localStorage.userId)
          //设置权限
          commit('SET_PERMISSION', hasPermissions)
          //设置当前用户
          commit('SET_USER', sysUser)
          //更新菜单
          commit('DoUpdateMenu', hasPermissions);

					return true
				}
			}
			return false
    },
    async logout({commit}, payload) {
      commit('SET_USER', {})
      commit('SET_PERMISSION', {})
      //删除服务在线信息
      return await api.logout()
    },
    async online({commit}, payload) {
      return api.online();
    },
    async lock({commit}, payload) {
      return api.lock();
    },
    async unlock({commit}, payload) {
      return api.unlock(payload);
    }
	}
}

export default app;
